package com.dhms.vostok1.model

import android.net.Uri
import android.util.Log
import androidx.core.net.toFile
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.dhms.vostok1.data.ApiResult
import com.dhms.vostok1.data.ApiState
import com.dhms.vostok1.service.net.NetworkApi
import okhttp3.MediaType
import okhttp3.RequestBody.Companion.asRequestBody

class MediaViewModel : ViewModel() {
    private val TAG = "MediaViewModel"
    private val _uploadFileResult = MutableLiveData<ApiResult?>(null)
    val uploadFileResult: LiveData<ApiResult?> = _uploadFileResult

    suspend fun uploadFile(file: Uri, mediaType: MediaType): String? {
        if (!file.toFile().exists()) {
            Log.i(TAG, "本地文件被删除")
            _uploadFileResult.value = ApiResult(ApiState.ERROR, "本地文件被删除")
            return null
        }
        _uploadFileResult.value = ApiResult(ApiState.LOADING)
        val fileName = file.path?.split("/")?.last() ?: ""
        val requestBody = file.toFile().asRequestBody(mediaType)
        val res = NetworkApi.uploadFileToOSS(requestBody, fileName)

        val e = res.exceptionOrNull()
        if (e != null) {
            _uploadFileResult.value = ApiResult(ApiState.ERROR, e.message)
            return null
        }

        // ref_id file in network could not be played in app so use name
//        val filePath = "/oss/file/${file.toFile().name}?ref_id=${res.getOrNull()?.body()?.data?.refId}"
        var filePath = res.getOrNull()?.body()?.data?.name
        _uploadFileResult.value = ApiResult(ApiState.DONE)

        return filePath
    }

}